const express = require('express');
const mysql = require('mysql');
const common = require('../../libs/common');
const jwt = require("jsonwebtoken");
const CryptoJS  = require("crypto-js");

var db = mysql.createPool({ host: 'localhost', user: 'root', password: '123456', database: 'hdadmin' });

function decrypt(content, key){
    var sKey = CryptoJS.enc.Utf8.parse(key);
    var decrypt = CryptoJS.AES.decrypt(content, sKey, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

module.exports = function () {
    var router = express.Router();
    router.post('/userlogin', (req, res) => {
        var username = req.query.loginName;
        //解密，加密过程看博客 https://l1334101793.gitee.io/记录vue-element的一些经验/
        var passwordSecret = decrypt(req.query.password,common.key);
        //md5加密，防拖库
        var password = common.md5(passwordSecret + common.MD5_SUFFIX);
        console.log(username)

        //用户是否为空
        if (username == '') {
          res.json({
            status: 'fail',
            data: {
              errorCode: '1'
            },
            errorMsg: '用户名不能为空'
          });
          return;
      }
      //密码是否为空
      else if (password == '') {
          res.json({
              status: 'fail',
              data: {
                errorCode: '2'
              },
              errorMsg: '密码不能为空'
          });
          return;
      }
      else {
          db.query(`SELECT * FROM admin_table WHERE admin_name='${username}' && admin_state='true'`, (err, data) => {
              if (err) {
                  res.status(500).send('数据库错误').end();
              }
              else {
                  if (data.length == 0) {
                      res.json({
                          status: 'fail',
                          data: {
                            errorCode: '3'
                          },
                          errorMsg: '没有找到该用户'
                      });
                      return;
                  }
                  else {
                      if (data[0].password == password) {
                        const rule = {id:data[0].GUID,name:username};
                        jwt.sign(rule,common.MD5_SUFFIX,{expiresIn:7200},(err,token) => {
                          if(err) throw err;
                          res.json({
                            code: 200,
                            status: 'success',
                            message: '登录成功',
                            username: username,
                            token:  "Bearer " + token
                          });
                        })
                      }
                      else {
                          res.json({
                              status: 'fail',
                              data: {
                                errorCode: '4'
                              },
                              errorMsg: '密码不正确'
                          });
                          return;
                      }
                  }
              }
          })
      }
    });
    return router;
}